package org.erp.spu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.log4j.Log4j2;
import org.erp.spu.entity.SpuModelTemplate;
import org.erp.spu.entity.SpuTemplateInfo;
import org.erp.spu.entity.SpuTemplateVersion;
import org.erp.spu.entity.dto.SpuTemplateReleaseDto;
import org.erp.spu.entity.vo.ReleaseGroupVo;
import org.erp.spu.entity.vo.ReleaseVo;
import org.erp.spu.entity.vo.ReleaseChildrenVo;
import org.erp.spu.entity.vo.SpuTemplateReleaseVo;
import org.erp.spu.mapper.SpuModelTemplateMapper;
import org.erp.spu.mapper.SpuTemplateInfoMapper;
import org.erp.spu.mapper.SpuTemplateReleaseMapper;
import org.erp.spu.mapper.SpuTemplateVersionMapper;
import org.erp.spu.service.SpuTemplateReleaseService;
import org.springframework.stereotype.Service;
import org.erp.spu.entity.SpuTemplateRelease;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Log4j2
@Service
public class SpuTemplateReleaseServiceImpl extends ServiceImpl<SpuTemplateReleaseMapper, SpuTemplateRelease> implements SpuTemplateReleaseService {
    @Resource
    private SpuTemplateReleaseMapper spuTemplateReleaseMapper;

    @Resource
    private SpuTemplateVersionMapper spuTemplateVersionMapper;

    @Resource
    private SpuTemplateInfoMapper spuTemplateInfoMapper;

    @Resource
    private SpuModelTemplateMapper spuModelTemplateMapper;




    /**
     * 根据模板id获取发布列表
     * @param templateId
     * @return
     */
    @Override
    public SpuTemplateReleaseVo getByTemplateId(Long templateId) {

        return spuTemplateReleaseMapper.getByTemplateId(templateId);
//         SpuTemplateReleaseVo spuTemplateReleaseVo=new SpuTemplateReleaseVo();
//         spuTemplateReleaseVo.setTemplateId(templateId);
//         //获取最新模板版本
//         SpuTemplateVersion templateVersion=getLastTemplateVersion(templateId);
//         if(templateVersion!=null){
//           Long templateVersionId =templateVersion.getId();
//           spuTemplateReleaseVo.setTemplateVersionId(templateVersionId);
//           List<SpuTemplateRelease> allList= spuTemplateReleaseMapper.selectList(new LambdaQueryWrapper<SpuTemplateRelease>()
//                   .eq(SpuTemplateRelease::getTemplateId, templateId)
//                   .eq(SpuTemplateRelease::getTemplateVersionId, templateVersionId)
//                   .eq(SpuTemplateRelease::getDelFlag, 0)
//                  );
//           if (allList != null && !allList.isEmpty()) {
//               List<ReleaseGroupVo> groupVos = allList.stream()
//                       .collect(Collectors.groupingBy(SpuTemplateRelease::getReleaseGroupId, LinkedHashMap::new, Collectors.toList()))
//                       .entrySet().stream()
//                       .map(groupEntry -> {
//                           Long groupId = groupEntry.getKey();
//                           List<SpuTemplateRelease> groupItems = groupEntry.getValue();
//                           ReleaseGroupVo gv = new ReleaseGroupVo();
//                           gv.setGroupId(groupId);
//                           String groupName = groupItems.stream()
//                                   .map(SpuTemplateRelease::getReleaseGroupName)
//                                   .filter(name -> name != null)
//                                   .findFirst()
//                                   .orElse(null);
//                           gv.setGroupName(groupName);
//
//                           Map<Long, List<SpuTemplateRelease>> byParent = groupItems.stream()
//                                   .collect(Collectors.groupingBy(
//                                           it -> {
//                                               Long pid = it.getReleaseParentId();
//                                               return pid != null ? pid : it.getReleaseId();
//                                           },
//                                           LinkedHashMap::new,
//                                           Collectors.toList()
//                                   ));
//
//                           List<ReleaseVo> releases = byParent.entrySet().stream()
//                                   .map(parentEntry -> {
//                                       List<SpuTemplateRelease> parentItems = parentEntry.getValue();
//                                       SpuTemplateRelease head = parentItems.get(0);
//
//                                       ReleaseVo rv = new ReleaseVo();
//                                       rv.setParentId(parentEntry.getKey());
//                                       String parentName = head.getReleaseParentName();
//                                       if (parentName == null) {
//                                           parentName = head.getReleaseName();
//                                       }
//                                       rv.setParentName(parentName);
//
//                                       List<ReleaseChildrenVo> children = parentItems.stream()
//                                               .filter(x -> x.getReleaseId() != null)
//                                               .collect(Collectors.toMap(
//                                                       SpuTemplateRelease::getReleaseId,
//                                                       x -> {
//                                                           ReleaseChildrenVo c = new ReleaseChildrenVo();
//                                                           c.setChildrenId(x.getReleaseId());
//                                                           c.setChildrenName(x.getReleaseName());
//                                                           return c;
//                                                       },
//                                                       (a, b) -> a,
//                                                       LinkedHashMap::new
//                                               ))
//                                               .values().stream().collect(Collectors.toList());
//                                       rv.setChildrenList(children);
//                                       return rv;
//                                   })
//                                   .collect(Collectors.toList());
//                           gv.setReleaseList(releases);
//                           return gv;
//                       })
//                       .collect(Collectors.toList());
//               spuTemplateReleaseVo.setGroupList(groupVos);
//           } else {
//               spuTemplateReleaseVo.setGroupList(new ArrayList<>());
//           }
//           return spuTemplateReleaseVo;
//        }else {
//            return spuTemplateReleaseVo;
//        }

    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean editSpuTemplateRelease(SpuTemplateReleaseDto spuTemplateReleaseDto) {
        Assert.notNull(spuTemplateReleaseDto.getTemplateId(),"模板id不能为空");
        SpuTemplateInfo templateInfo=spuTemplateInfoMapper.selectById(spuTemplateReleaseDto.getTemplateId());
        Assert.notNull(templateInfo,"模板不存在");
        Assert.notNull(spuTemplateReleaseDto.getTemplateReleaseList(),"模板发布项不能为空");
        SpuTemplateVersion templateVersion=getLastTemplateVersion(spuTemplateReleaseDto.getTemplateId());
        SpuTemplateVersion version=new SpuTemplateVersion();

        version.setTemplateId(spuTemplateReleaseDto.getTemplateId());
        if(templateVersion==null) {
            version.setVersionNo(1);
        }else{
            version.setVersionNo(templateVersion.getVersionNo()+1);
        }
         spuTemplateVersionMapper.insert(version);
         log.info("保存模板版本：{}",version);
         templateInfo.setActiveVersionId(version.getId());
         spuTemplateReleaseDto.getTemplateReleaseList().forEach(releaseInfoDto -> {
            SpuTemplateRelease release=new SpuTemplateRelease();
            release.setTemplateName(templateInfo.getTemplateName());
            release.setTemplateId(spuTemplateReleaseDto.getTemplateId());
            release.setTemplateVersionId(version.getId());
            release.setReleaseGroupId(releaseInfoDto.getReleaseGroupId());
            release.setReleaseGroupName(releaseInfoDto.getReleaseGroupName());
            release.setReleaseParentId(releaseInfoDto.getReleaseParentId());
            release.setReleaseParentName(releaseInfoDto.getReleaseParentName());
            release.setReleaseId(releaseInfoDto.getReleaseId());
            release.setReleaseName(releaseInfoDto.getReleaseName());
            spuTemplateReleaseMapper.insert(release);
            log.info("保存模板发布项：{}",release);
        });
        return true;
    }

    @Override
    public SpuTemplateReleaseVo getByModelId(Long modelId) {
        //获取最新的模版
        SpuModelTemplate spuModelTemplate = spuModelTemplateMapper.selectOne(new LambdaQueryWrapper<SpuModelTemplate>()
                .eq(SpuModelTemplate::getModelId, modelId)
                .eq(SpuModelTemplate::getDelFlag, 0));
        return getByTemplateId(spuModelTemplate.getTemplateId());
    }


    /**
     * 根据模板id获取最新模板版本
     * @param templateId
     * @return
     */
    private  SpuTemplateVersion getLastTemplateVersion(Long templateId){
        SpuTemplateVersion templateVersion=spuTemplateVersionMapper
                .selectOne(new LambdaQueryWrapper<SpuTemplateVersion>().eq(SpuTemplateVersion::getTemplateId, templateId)
                        .eq(SpuTemplateVersion::getDelFlag, 0).orderByDesc(SpuTemplateVersion::getVersionNo)
                        .last("limit 1"));
        return templateVersion;
    }
}
